// 运行时配置
import { RequestConfig, history } from '@umijs/max';
import { message } from 'antd';
import 'antd/dist/reset.css';
import { debounce } from 'lodash';
import qs from 'qs';
import './dh.css';

const showError = debounce(
  (msg: string) => {
    message.error(msg);
  },
  3000,
  { leading: true },
);

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ name: string }> {
  return { name: '@umijs/max' };
}

export const request: RequestConfig = {
  timeout: 30000,
  // other axios options you want
  errorConfig: {
    errorHandler() {},
    errorThrower() {},
  },
  requestInterceptors: [
    (url, options) => {
      const local = JSON.parse(localStorage.getItem('auth') || 'null');
      if (local) {
        options.headers = {
          ...options.headers,
          Authorization: local.token,
        };
      }
      options.paramsSerializer = (params: any) => {
        return qs.stringify(params, { arrayFormat: 'repeat' });
      };

      return { url, options };
    },
  ],
  responseInterceptors: [
    (res) => {
      const { data } = res as any;
      console.log(data,111111)
      if (!data) {
        // showError('请求失败！');
      } else if (
        data?.code === 402 ||
        data?.code === 401 ||
        data?.code === 404 ||
        data?.code === 4001
      ) {
        showError('登录过期, 请重新登录');
        setTimeout(() => {
          history.push('/login');
          localStorage.clear();
        }, 2000);
      } else if (data?.code === 604) {
        showError(data.message);
        setTimeout(() => {
          history.push('/login');
          localStorage.clear();
        }, 2000);
      }
      return res;
    },
  ],
};
